package com.lagou.rocket.demo.order;

import com.lagou.rocket.demo.order.model.Order;
import com.lagou.rocket.demo.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;

/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-11-07
 */
@Slf4j
//@RocketMQTransactionListener(txProducerGroup = "orderservice_producer_tx")
public class CheckPayTransactionListener implements RocketMQLocalTransactionListener {


    private final PlatformTransactionManager transactionManager;

    private final IOrderService orderService;

    public CheckPayTransactionListener(PlatformTransactionManager transactionManager, IOrderService orderService) {
        this.transactionManager = transactionManager;
        this.orderService = orderService;

    }


    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {


        try {
            // 提交事务
            log.info("提交本地事务....");
            TransactionStatus transactionStatus = (TransactionStatus) arg;
            transactionManager.commit(transactionStatus);

        } catch (Exception e) {
            log.error("事务提交失败", e);
            return RocketMQLocalTransactionState.ROLLBACK;
        }


        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        Long orderId = (Long)msg.getPayload();
        // 确认数据库事务是否提交成功
        //      检查这个订单已经成功保存
        Order order = orderService.getOne(orderId);
        if (order != null && !"sell_out".equals(order.getStatus())){
            return RocketMQLocalTransactionState.COMMIT;
        }

        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
